<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">


<meta name="google-site-verification" content="E9deYnivN5MuHMuIfiMZZfS0alv-d_0UjcwjBL79lGU" />



<meta name="baidu-site-verification" content="iHYWJxscwD" />










<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />



  <meta name="google-site-verification" content="true" />








  <meta name="baidu-site-verification" content="true" />







  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Python,量化投资,编程难题,MIT,列表,排序," />










<meta name="description" content="《programming for the puzzled》第二章题目描述:一个聚会不同的人抵达和离开的时间的列表，其中的时间是前闭后开的，即如果你在结束的时间点到达，也会错过这个人。你只有一个小时，找到最佳的参加聚会的时间，使得碰到的人最多。以一个tuple列表来表示不同的人参加聚会时间区间。sched &#x3D; [(6, 8), (6, 12), (6, 7), (7, 8), (7, 10), (8">
<meta property="og:type" content="article">
<meta property="og:title" content="量化投资学习笔记47——通过问题学算法:02聚会的最佳时间(the best time to party)">
<meta property="og:url" content="https://zwdnet.github.io/2020/05/03/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B047%E2%80%94%E2%80%94%E9%80%9A%E8%BF%87%E9%97%AE%E9%A2%98%E5%AD%A6%E7%AE%97%E6%B3%95-02%E8%81%9A%E4%BC%9A%E7%9A%84%E6%9C%80%E4%BD%B3%E6%97%B6%E9%97%B4-the-best-time-to-party/index.html">
<meta property="og:site_name" content="赵瑜敏的口腔医学专业学习博客">
<meta property="og:description" content="《programming for the puzzled》第二章题目描述:一个聚会不同的人抵达和离开的时间的列表，其中的时间是前闭后开的，即如果你在结束的时间点到达，也会错过这个人。你只有一个小时，找到最佳的参加聚会的时间，使得碰到的人最多。以一个tuple列表来表示不同的人参加聚会时间区间。sched &#x3D; [(6, 8), (6, 12), (6, 7), (7, 8), (7, 10), (8">
<meta property="og:locale">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/35/01.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/wx.jpg">
<meta property="article:published_time" content="2020-05-03T01:31:19.000Z">
<meta property="article:modified_time" content="2020-08-30T05:52:04.000Z">
<meta property="article:author" content="赵瑜敏">
<meta property="article:tag" content="Python">
<meta property="article:tag" content="量化投资">
<meta property="article:tag" content="编程难题">
<meta property="article:tag" content="MIT">
<meta property="article:tag" content="列表">
<meta property="article:tag" content="排序">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/35/01.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zwdnet.github.io/2020/05/03/量化投资学习笔记47——通过问题学算法-02聚会的最佳时间-the-best-time-to-party/"/>





  <title>量化投资学习笔记47——通过问题学算法:02聚会的最佳时间(the best time to party) | 赵瑜敏的口腔医学专业学习博客</title>
  








<meta name="generator" content="Hexo 5.4.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">赵瑜敏的口腔医学专业学习博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zwdnet.github.io/2020/05/03/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B047%E2%80%94%E2%80%94%E9%80%9A%E8%BF%87%E9%97%AE%E9%A2%98%E5%AD%A6%E7%AE%97%E6%B3%95-02%E8%81%9A%E4%BC%9A%E7%9A%84%E6%9C%80%E4%BD%B3%E6%97%B6%E9%97%B4-the-best-time-to-party/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/tx.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="赵瑜敏的口腔医学专业学习博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">量化投资学习笔记47——通过问题学算法:02聚会的最佳时间(the best time to party)</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-05-03T01:31:19+00:00">
                2020-05-03
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84/" itemprop="url" rel="index">
                    <span itemprop="name">量化投资</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                  <span class="post-meta-divider">|</span>
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  1.7k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  7
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>《programming for the puzzled》第二章<br>题目描述:一个聚会不同的人抵达和离开的时间的列表，其中的时间是前闭后开的，即如果你在结束的时间点到达，也会错过这个人。你只有一个小时，找到最佳的参加聚会的时间，使得碰到的人最多。<br>以一个tuple列表来表示不同的人参加聚会时间区间。<br>sched = [(6, 8), (6, 12), (6, 7), (7, 8), (7, 10), (8, 9), (8, 10), (9, 12), (9, 10), (10, 11), (10, 12), (11, 12)]<br>先自己做一下吧。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># coding:utf-8</span></span><br><span class="line"><span class="comment"># 《programming for the puzzled》实操</span></span><br><span class="line"><span class="comment"># 参加聚会的最佳时间</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 自己的方法</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">bestTime</span>(<span class="params">sched</span>):</span></span><br><span class="line">    n = <span class="built_in">len</span>(sched)</span><br><span class="line">    start = []</span><br><span class="line">    end = []</span><br><span class="line">    <span class="keyword">for</span> t <span class="keyword">in</span> sched:</span><br><span class="line">        start.append(t[<span class="number">0</span>])</span><br><span class="line">        end.append(t[<span class="number">1</span>])</span><br><span class="line">    minTime = <span class="built_in">min</span>(start) <span class="comment"># 最早的开始时间</span></span><br><span class="line">    maxTime = <span class="built_in">max</span>(end) <span class="comment"># 最晚的结束时间</span></span><br><span class="line">    max_time = <span class="number">0</span></span><br><span class="line">    result = minTime</span><br><span class="line">    <span class="keyword">for</span> time <span class="keyword">in</span> <span class="built_in">range</span>(minTime, maxTime):</span><br><span class="line">        times = <span class="number">0</span></span><br><span class="line">        <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(n):</span><br><span class="line">            <span class="keyword">if</span> time &gt;= start[i] <span class="keyword">and</span> time+<span class="number">1</span> &lt;= end[i]:</span><br><span class="line">                times += <span class="number">1</span></span><br><span class="line">        <span class="keyword">if</span> times &gt; max_time:</span><br><span class="line">            max_time = times</span><br><span class="line">            result = time</span><br><span class="line">        times = <span class="number">0</span></span><br><span class="line">    print(max_time)</span><br><span class="line">    <span class="keyword">return</span> result</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&quot;__main__&quot;</span>:</span><br><span class="line">    sched = [(<span class="number">6</span>, <span class="number">8</span>), (<span class="number">6</span>, <span class="number">12</span>), (<span class="number">6</span>, <span class="number">7</span>), (<span class="number">7</span>, <span class="number">8</span>), (<span class="number">7</span>, <span class="number">10</span>), (<span class="number">8</span>, <span class="number">9</span>), (<span class="number">8</span>, <span class="number">10</span>), (<span class="number">9</span>, <span class="number">12</span>), (<span class="number">9</span>, <span class="number">10</span>), (<span class="number">10</span>, <span class="number">11</span>), (<span class="number">10</span>, <span class="number">12</span>), (<span class="number">11</span>, <span class="number">12</span>)]</span><br><span class="line">    <span class="comment"># 自己的方法</span></span><br><span class="line">    result = bestTime(sched)</span><br><span class="line">    print(<span class="string">&quot;最佳时间:&quot;</span>, result)</span><br></pre></td></tr></table></figure>
<p>用的穷举，两层循环。结果是9点去，可以碰到5个人。<br>再来看看作者的分析。思路跟我一样的，穷举。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 作者的第一个算法，也是穷举</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">bestTimeToParty</span>(<span class="params">schedule</span>):</span></span><br><span class="line">    start = schedule[<span class="number">0</span>][<span class="number">0</span>]</span><br><span class="line">    end = schedule[<span class="number">0</span>][<span class="number">1</span>]</span><br><span class="line">    <span class="keyword">for</span> c <span class="keyword">in</span> schedule:</span><br><span class="line">        start = <span class="built_in">min</span>(c[<span class="number">0</span>], start)</span><br><span class="line">        end = <span class="built_in">max</span>(c[<span class="number">1</span>], end)</span><br><span class="line">        count = celebrityDensity(schedule, start, end)</span><br><span class="line">        maxcount = <span class="number">0</span></span><br><span class="line">        <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(start, end+<span class="number">1</span>):</span><br><span class="line">            <span class="keyword">if</span> count[i] &gt; maxcount:</span><br><span class="line">                maxcount = count[i]</span><br><span class="line">                time = i</span><br><span class="line">    print(<span class="string">&quot;到达party的最佳时间为&quot;</span>, time, <span class="string">&quot;点，有&quot;</span>, maxcount, <span class="string">&quot;个人抵达。&quot;</span>)</span><br><span class="line">        </span><br><span class="line">        </span><br><span class="line"><span class="comment"># 工具函数</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">celebrityDensity</span>(<span class="params">sched, start, end</span>):</span></span><br><span class="line">    count = [<span class="number">0</span>]*(end+<span class="number">1</span>)</span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(start, end+<span class="number">1</span>):</span><br><span class="line">        count[i] = <span class="number">0</span></span><br><span class="line">        <span class="keyword">for</span> c <span class="keyword">in</span> sched:</span><br><span class="line">            <span class="keyword">if</span> c[<span class="number">0</span>] &lt;= i <span class="keyword">and</span> c[<span class="number">1</span>] &gt; i:</span><br><span class="line">                count[i] += <span class="number">1</span></span><br><span class="line">    <span class="keyword">return</span> count</span><br></pre></td></tr></table></figure>
<p>运行结果跟我是一样的，几个要点。<br>输入的数据不能更改，因此用tuple。<br>那个工具函数是计算到目前为止的时间区间内能遇到的人数，貌似有重复计算的。<br>程序的问题:如果时间不是整数，而是任意时间，如果精确到分钟，遍历次数会膨胀60倍，如果到秒，微秒呢……考虑一个不依赖时间粒度的算法。<br>这个我就想不出来了，看作者的程序吧。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 处理更细的时间</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">bestTimeToPartySmart</span>(<span class="params">schedule</span>):</span></span><br><span class="line">    times = []</span><br><span class="line">    <span class="keyword">for</span> c <span class="keyword">in</span> schedule:</span><br><span class="line">        times.append((c[<span class="number">0</span>], <span class="string">&quot;start&quot;</span>))</span><br><span class="line">        timed.append((c[<span class="number">1</span>], <span class="string">&quot;end&quot;</span>))</span><br><span class="line">    sortList(times)</span><br><span class="line">    maxCount, time = chooseTime(times)</span><br><span class="line">    print(<span class="string">&quot;到达聚会的最佳时间为&#123;&#125;点，能遇到&#123;&#125;个人。&quot;</span>.<span class="built_in">format</span>(time, maxCount))</span><br><span class="line"></span><br><span class="line"><span class="comment"># 改进，处理更细的时间段</span></span><br><span class="line">sched2 = [(<span class="number">6.0</span>, <span class="number">8.0</span>), (<span class="number">6.5</span>, <span class="number">12.0</span>), (<span class="number">6.5</span>, <span class="number">7.0</span>), (<span class="number">7.0</span>, <span class="number">8.0</span>), (<span class="number">7.5</span>, <span class="number">10.0</span>), (<span class="number">8.0</span>, <span class="number">9.0</span>), (<span class="number">8.0</span>, <span class="number">10.0</span>), (<span class="number">9.0</span>, <span class="number">12.0</span>), (<span class="number">9.5</span>, <span class="number">10.0</span>), (<span class="number">10.0</span>, <span class="number">11.0</span>), (<span class="number">10.0</span>, <span class="number">12.0</span>), (<span class="number">11.0</span>, <span class="number">12.0</span>)]</span><br><span class="line">bestTimeToPartySmart(sched2)</span><br></pre></td></tr></table></figure>
<p>可以处理更细的时间了，思路是将所有人的赴约计划看成一条时间线，我自己的赴约时间与他们的时间线重合则能与他们相遇。于是只要看时间点的起止就行了。<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/35/01.png"><br>先根据日程取出时间区间的起止点，对这个列表排序，在找出赴约时间和能见到的最大人数。输入数据是浮点数而不是整数。<br>下面实现排序和选择函数</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 对列表排序</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">sortList</span>(<span class="params">tlist</span>):</span></span><br><span class="line">    <span class="keyword">for</span> ind <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">len</span>(tlist)-<span class="number">1</span>):</span><br><span class="line">        iSm = ind</span><br><span class="line">        <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(ind, <span class="built_in">len</span>(tlist)):</span><br><span class="line">            <span class="keyword">if</span> tlist[iSm][<span class="number">0</span>] &gt; tlist[i][<span class="number">0</span>]:</span><br><span class="line">                iSm = i</span><br><span class="line">        tlist[ind], tlist[iSm] = tlist[iSm], tlist[ind]</span><br><span class="line">        </span><br><span class="line">        </span><br><span class="line"><span class="comment"># 选择时间</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">chooseTime</span>(<span class="params">times</span>):</span></span><br><span class="line">    rcount = <span class="number">0</span></span><br><span class="line">    maxcount = time = <span class="number">0</span></span><br><span class="line">    <span class="keyword">for</span> t <span class="keyword">in</span> times:</span><br><span class="line">        <span class="keyword">if</span> t[<span class="number">1</span>] == <span class="string">&quot;start&quot;</span>:</span><br><span class="line">            rcount += <span class="number">1</span></span><br><span class="line">        <span class="keyword">elif</span> t[<span class="number">1</span>] == <span class="string">&quot;end&quot;</span>:</span><br><span class="line">            rcount -= <span class="number">1</span></span><br><span class="line">        <span class="keyword">if</span> rcount &gt; maxcount:</span><br><span class="line">            maxcount = rcount</span><br><span class="line">            time = t[<span class="number">0</span>]</span><br><span class="line">    <span class="keyword">return</span> maxcount, time</span><br></pre></td></tr></table></figure>
<p>排序用的是选择排序，排序完成以后进行选择，方法是挨个取出排序好的列表中的元素，如果是抵达时间，计数器加一，如果是离开时间，计数器减一，并记录当前的最大相遇人数和取到最大值时的时间（因为当取值最大时，一定只能是抵达时间而不是离开时间）。<br>这样只要对列表遍历一遍就行了，而不是像第一个算法那样遍历两遍。但是选择排序的时间复杂度还是O(n²)。用其它排序方法可以优化到O(nlogn)。<br>练习1.假如你非常忙，只能在[ystart, yend)时间段内参加聚会，求你能见到的最多的人数。<br>在chooseTime函数的判断力增加时间限制即可。<br>if rcount &gt; maxcount  and t[0] &gt;= ystart and t[0] &lt; yend:<br>练习2.另一个不依赖时间粒度的算法:依次检查每个参加者的时间区间，看这个参加者的到达时间在多少其它参加者的时间区间内。选择最多的那位参与者的抵达时间。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 练习2.另一种不依赖时间粒度的算法</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">bestTimeToPartySmart3</span>(<span class="params">schedule</span>):</span></span><br><span class="line">    maxCount = <span class="number">0</span></span><br><span class="line">    time = <span class="number">0</span></span><br><span class="line">    n = <span class="built_in">len</span>(schedule)</span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(n):</span><br><span class="line">        count = <span class="number">0</span></span><br><span class="line">        start = schedule[i][<span class="number">0</span>]</span><br><span class="line">        <span class="keyword">for</span> j <span class="keyword">in</span> <span class="built_in">range</span>(n):</span><br><span class="line">            <span class="keyword">if</span> schedule[j][<span class="number">0</span>] &lt;= start <span class="keyword">and</span> schedule[j][<span class="number">1</span>] &gt; start:</span><br><span class="line">                count += <span class="number">1</span></span><br><span class="line">        <span class="keyword">if</span> count &gt; maxCount:</span><br><span class="line">            maxCount = count</span><br><span class="line">            time = start</span><br><span class="line">    print(<span class="string">&quot;到达聚会的最佳时间为&#123;&#125;点，能遇到&#123;&#125;个人。&quot;</span>.<span class="built_in">format</span>(time, maxCount))</span><br></pre></td></tr></table></figure>
<p>练习3.设想用一个数字表示你有多想见一位嘉宾，用一个三维的tuple表示，如(6.0, 8.0, 3)表示Ta六点到，8点离开，你想见Ta的程度为3。修改程序，找到你的抵达时间，使得权重值最大化（而不是人数）。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 练习3，使自己见到的嘉宾权重最大</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">bestTimeToPartySmart4</span>(<span class="params">schedule</span>):</span></span><br><span class="line">    maxWeight = <span class="number">0</span></span><br><span class="line">    time = <span class="number">0</span></span><br><span class="line">    n = <span class="built_in">len</span>(schedule)</span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(n):</span><br><span class="line">        weight = <span class="number">0</span></span><br><span class="line">        start = schedule[i][<span class="number">0</span>]</span><br><span class="line">        <span class="keyword">for</span> j <span class="keyword">in</span> <span class="built_in">range</span>(n):</span><br><span class="line">            <span class="keyword">if</span> schedule[j][<span class="number">0</span>] &lt;= start <span class="keyword">and</span> schedule[j][<span class="number">1</span>] &gt; start:</span><br><span class="line">                weight += schedule[j][<span class="number">2</span>]</span><br><span class="line">        <span class="keyword">if</span> weight &gt; maxWeight:</span><br><span class="line">            maxWeight = weight</span><br><span class="line">            time = start</span><br><span class="line">    print(<span class="string">&quot;到达聚会的最佳时间为&#123;&#125;点，最大权重值为&#123;&#125;。&quot;</span>.<span class="built_in">format</span>(time, maxWeight))</span><br><span class="line"></span><br><span class="line"><span class="comment"># 练习3，使自己见到的嘉宾权重最大</span></span><br><span class="line">sched3 = [(<span class="number">6.0</span>, <span class="number">8.0</span>, <span class="number">2</span>), (<span class="number">6.5</span>, <span class="number">12.0</span>, <span class="number">1</span>), (<span class="number">6.5</span>, <span class="number">7.0</span>, <span class="number">2</span>), (<span class="number">7.0</span>, <span class="number">8.0</span>, <span class="number">2</span>), (<span class="number">7.5</span>, <span class="number">10.0</span>, <span class="number">3</span>), (<span class="number">8.0</span>, <span class="number">9.0</span>, <span class="number">2</span>), (<span class="number">8.0</span>, <span class="number">10.0</span>, <span class="number">1</span>), (<span class="number">9.0</span>, <span class="number">12.0</span>, <span class="number">2</span>), (<span class="number">9.5</span>, <span class="number">10.0</span>, <span class="number">4</span>), (<span class="number">10.0</span>, <span class="number">11.0</span>, <span class="number">2</span>), (<span class="number">10.0</span>, <span class="number">12.0</span>, <span class="number">3</span>), (<span class="number">11.0</span>, <span class="number">12.0</span>, <span class="number">7</span>)]</span><br><span class="line">bestTimeToPartySmart4(sched3)</span><br></pre></td></tr></table></figure>
<p>就是把原来记次的地方改成累加权重。输出的结果是在11点抵达，最大权重值为13。跟书中的结果一样。<br>本章完成。b站上的课程视频的中文字幕貌似是机器翻译的，还不如没有呢。</p>
<p>我发文章的三个地方，欢迎大家在朋友圈等地方分享，欢迎点“在看”。<br>我的个人博客地址：<a href="https://zwdnet.github.io/">https://zwdnet.github.io</a><br>我的知乎文章地址： <a target="_blank" rel="noopener" href="https://www.zhihu.com/people/zhao-you-min/posts">https://www.zhihu.com/people/zhao-you-min/posts</a><br>我的微信个人订阅号：赵瑜敏的口腔医学学习园地</p>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/wx.jpg"></p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>欢迎打赏！感谢支持！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/mm_facetoface_collect_qrcode_1542944836634.png" alt=" 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/1542944857770.jpg" alt=" 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Python/" rel="tag"># Python</a>
          
            <a href="/tags/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84/" rel="tag"># 量化投资</a>
          
            <a href="/tags/%E7%BC%96%E7%A8%8B%E9%9A%BE%E9%A2%98/" rel="tag"># 编程难题</a>
          
            <a href="/tags/MIT/" rel="tag"># MIT</a>
          
            <a href="/tags/%E5%88%97%E8%A1%A8/" rel="tag"># 列表</a>
          
            <a href="/tags/%E6%8E%92%E5%BA%8F/" rel="tag"># 排序</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2020/05/02/%E4%BD%A0%E4%BC%9A%E5%A4%87%E7%89%99%E5%90%97%E2%80%94%E2%80%94%E5%89%8D%E7%89%99%E5%85%A8%E5%86%A0%E7%89%99%E4%BD%93%E9%A2%84%E5%A4%87%EF%BC%88%E7%BB%AD%EF%BC%89/" rel="next" title="你会备牙吗——前牙全冠牙体预备（续）">
                <i class="fa fa-chevron-left"></i> 你会备牙吗——前牙全冠牙体预备（续）
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2020/05/05/%E7%89%99%E9%AB%93%E7%97%85%E6%80%BB%E7%BB%9317%E2%80%94%E2%80%94%E6%A0%B9%E7%AE%A1%E6%B2%BB%E7%96%97%E7%9A%84%E9%A2%84%E5%90%8E/" rel="prev" title="牙髓病总结17——根管治疗的预后">
                牙髓病总结17——根管治疗的预后 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC80MTA2Mi8xNzU4Nw=="></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/tx.jpg"
                alt="" />
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/%20%7C%7C%20archive">
              
                  <span class="site-state-item-count">452</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">29</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">544</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">本站版权归赵瑜敏所有，如欲转载请与本人联系。</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">1225.8k</span>
  
</div>









<div>
  <script type="text/javascript">var cnzz_protocol = (("https:" == document.location.protocol) ? " https://" : " http://");document.write(unescape("%3Cspan id='cnzz_stat_icon_1275447216'%3E%3C/span%3E%3Cscript src='" + cnzz_protocol + "s11.cnzz.com/z_stat.php%3Fid%3D1275447216%26online%3D1%26show%3Dline' type='text/javascript'%3E%3C/script%3E"));</script>
</div>

        







  <div style="display: none;">
    <script src="//s95.cnzz.com/z_stat.php?id=1275447216&web_id=1275447216" language="JavaScript"></script>
  </div>



        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  





  

  

  

  
  

  

  

  

  
</body>
</html>
